﻿using System;
using System.ComponentModel.Composition;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;

namespace Songhay.OpenXml.Transformations
{
    using Songhay.OpenXml.Models;

    /// <summary>
    /// Transforms the Open XML WordML text
    /// and translates selected characters.
    /// </summary>
    [Export(typeof(IWordProcessingDocumentTransformation))]
    public class TextAndCharactersTransformation : IWordProcessingDocumentTransformation
    {
        #region IWordProcessingDocumentTransformation Members

        /// <summary>
        /// Gets or sets the execution ordinal.
        /// </summary>
        /// <value>The execution ordinal.</value>
        public byte ExecutionOrdinal { get; set; }

        /// <summary>
        /// Determines whether this instance can transform the specified word doc.
        /// </summary>
        /// <param name="wordDoc">The Word document.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="node">The node.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can transform the specified word doc; otherwise, <c>false</c>.
        /// </returns>
        public bool CanTransform(WordprocessingDocument wordDoc, SonghayHtmlConverterSettings settings, XNode node)
        {
            return this.HasElementName(node, SonghayW.br) ||
                this.HasElementName(node, SonghayW.cr) ||
                this.HasElementName(node, SonghayW.noBreakHyphen) ||
                this.HasElementName(node, SonghayW.t);
        }

        /// <summary>
        /// Transforms the specified Word document.
        /// </summary>
        /// <param name="wordDoc">The Word document.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="node">The node.</param>
        /// <param name="imageHandler">The image handler.</param>
        public object Transform(WordprocessingDocument wordDoc,
            SonghayHtmlConverterSettings settings,
            XNode node, Func<ImageInfo, XElement> imageHandler)
        {
            var element = node as XElement;

            // Transform every w:t element to a text node.
            if(element.Name == SonghayW.t)
                return OpenXmlUtility.TranslateEntities(element.Value, settings);

            // Transform w:br to h:br.
            if((element.Name == SonghayW.br) || (element.Name == SonghayW.cr))
                return new XElement(SonghayXhtml.br);

            if(element.Name == SonghayW.noBreakHyphen)
                return new XText("-");

            return null;
        }

        #endregion
    }
}
